//
//  TimeLine.mm
//  TwitPlane
//
//  Created by kazuyuki takahashi on 11/09/09.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include <boost/cast.hpp>
#import "TimeLine.h"
#import "TwitterEngine.h"
#import "Status.h"

@implementation Timeline

- (id)init
{
    self = [super init];
    if (self) {
        mStatuses = [[NSMutableArray alloc] init];
    }
    
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [mEngine release];
    [mStatuses release];
    [super dealloc];
}

#pragma mark - Property Accessors

- (void)setTwitterEngine:(TwitterEngine *)twitterEngine {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [mEngine autorelease];
    [center removeObserver:self];
    
    mEngine = [twitterEngine retain];
    [center addObserver:self 
               selector:@selector(statusReceived:)
                   name:kTwitterEngineDidReceiveStatusNotification
                 object:mEngine];
}

- (TwitterEngine*)twitterEngine {
    return mEngine;
}
     
#pragma mark - Other Public Methods

- (NSUInteger)count {
    return [mStatuses count];
}

#pragma mark - Private Methods

- (void)statusReceived:(NSNotification*)notification {
    Status *s = [[notification userInfo] objectForKey:@"status"];
    NSParameterAssert([s isKindOfClass:[Status class]]);
    
    //常に降順ソートされているようにする
    
    NSComparator cmp = ^(id s0, id s1) {
        StatusID id0 = [s0 sid];
        StatusID id1 = [s1 sid];
        if (id0 > id1) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        if (id0 < id1) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    
    NSUInteger idx = [mStatuses indexOfObject:s
                                inSortedRange:NSMakeRange(0, [mStatuses count])
                                      options:NSBinarySearchingInsertionIndex
                              usingComparator:cmp];
    [mStatuses insertObject:s atIndex:idx];
}

- (Status*)statusAtIndex:(NSUInteger)index {
    NSParameterAssert(0 <= index && index < [self count]);
    return [mStatuses objectAtIndex:index];
}

@end
